#! /usr/bin/env python
# coding=utf-8


import random
from argparse import RawTextHelpFormatter
import sys
import argparse




parser = argparse.ArgumentParser(
    description='''
    根据pasa的结果 获取 glimmer的训练文件
    用法：
    glimmer_trainning_file.py -i trainingSetComplete.gff3 -l nonred.lst -o training_file
    
    ''',formatter_class=RawTextHelpFormatter)



parser.add_argument('-i',
                help='trainingSetComplete.gff3')

parser.add_argument('-l',
                help='nonred.lst 一列目标序列')

parser.add_argument('-o',
                help='输出的文件')




args = parser.parse_args()



if not args.i or not args.l  or not args.o:

    parser.print_help()

    sys.exit()




infile = args.i #r'trainingSetComplete.gff3'
lista_file = args.l #r'nonred.lst'
outfile = args.o #r'training_file'

dic = {}
dir_lista = {}
scf_dic = {}
with open(infile) as fila:
    for i in fila:
        line = i.strip()
        if line[0]!='#':
            k = line.split('\t')
            if len(k)>5 and k[2]=='CDS':
                
                ID = k[8].split(';')[0].split('=')[1]
                d = k[6]
                scaf = k[0]
                scf_dic[ID] = scaf
                dir_lista[ID] = d
                if d == '+':
                    l = [k[3],k[4]]
                else:
                    l = [k[4],k[3]]

                if ID not in dic:
                    dic[ID] = [l]
                else:
                    dic[ID] = dic[ID]+[l]

for i in dic:
    if dir_lista[i] == '+':
        dic[i] = sorted(dic[i],key=lambda x:int(x[0]))
    else:
        dic[i] = sorted(dic[i],key=lambda x:-int(x[0]))

t = 1

lista = []
with open(lista_file) as fila:
    for i in fila:
        if i.strip()!='':
            lista.append(i.strip())

final_lista =[]
size = 1000

for i in lista:
    if len(dic[i])>=5:
        final_lista.append((scf_dic[i],dic[i]))

        

final_lista = sorted(final_lista,key=lambda x:(x[0],int(x[1][0][0])))


t = sorted(random.sample(range(0,len(final_lista)),10))
#print(len(final_lista))

select_lista = [final_lista[x] for x in t]
with open(outfile,'w') as fila:
    for i in final_lista:
        scaf = i[0]
        for j in i[1]:
            fila.write(scaf+' '+str(j[0])+' '+str(j[1])+'\n')
        fila.write('\n')